<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		 <div>
		   debounce:<input type="text" id="debounce-input" />
		   <button id="cancel-btn">取消防抖</button>
		   <button id="del-btn">删除防抖</button>
		</div>
		<script>
		const inputDom = document.getElementById('debounce-input')
		const cancelBtnDom = document.getElementById('cancel-btn')
		const deleteBtnDom = document.getElementById("del-btn")
		
		function debounce(func, wait) {
		  let timeout
		  let del = false;
		  let debounced = function () {
		    const that = this // 改变执行函数内部 this 的指向
		    const args = arguments // 解决 doSomeThing event指向问题
			if(del){
				func.apply(that, args);
				return ;
			}
		    clearTimeout(timeout)
		    timeout = setTimeout(function () {
		      func.apply(that, args)
		    }, wait)
		  }
		  debounced.cancel = function () {
		    // 新增取消方法
		    clearTimeout(timeout)
		    timeout = null
		  }
		  debounced.delete = function(){
			  del = true;
		  }
		
		  return debounced
		}
		
		function doSomeThing(e) {
		  console.log('我是防抖～～～')
		  // console.log(e)
		  // console.log(this);
		  // 可能会做 回调 或者 ajax 请求
		}
		
		const doDebounce = debounce(doSomeThing, 5000, true)
		
		inputDom.onkeyup = doDebounce
		
		cancelBtnDom.onclick = function () {
		  doDebounce.cancel()
		}
		
		
		deleteBtnDom.onclick = function(){
			doDebounce.delete()
		}
		</script>
	</body>
</html>
